#include <iostream>
#include <memory>       // for shared_ptr, weak_ptr
#include <vector>
#include <algorithm>

// 观察者接口
class Observer;

// 主题接口
class Subject {
public:
    virtual void attach(std::shared_ptr<Observer> observer) = 0;
    virtual void detach(std::shared_ptr<Observer> observer) = 0;
    virtual void notify() = 0;
    virtual ~Subject() = default;
};

class Observer {
public:
    virtual void update(const std::string& message) = 0;
    virtual ~Observer() = default;
};

// 具体主题类
class ConcreteSubject : public Subject {
private:
    std::string state;
    std::vector<std::weak_ptr<Observer>> observers;  // 使用 weak_ptr 避免循环引用

public:
    void setState(const std::string& newState) {
        state = newState;
        notify();
    }

    void attach(std::shared_ptr<Observer> observer) override {
        observers.push_back(observer);  // 自动转换为 weak_ptr 存储
    }

    void detach(std::shared_ptr<Observer> observer) override {
        observers.erase(
            std::remove_if(observers.begin(), observers.end(),
                [&](const std::weak_ptr<Observer>& wp) {
                    return wp.lock() == observer;
                }),
            observers.end()
        );
    }

    void notify() override {
        for (auto it = observers.begin(); it != observers.end();) {
            if (auto observer = it->lock()) {  // 检查观察者是否还存在
                observer->update(state);
                ++it;
            } else {
                it = observers.erase(it);  // 移除已销毁的观察者
            }
        }
    }
};

// 具体观察者类
class ConcreteObserver : public Observer {
private:
    std::string name;

public:
    ConcreteObserver(const std::string& name) : name(name) {}

    void update(const std::string& message) override {
        std::cout << "Observer [" << name << "] received: " << message << std::endl;
    }
};